﻿using System;
using Quartz.Core;
using ZilLion.Core.ConfigManager.Manager;
using ZilLion.TaskManager.Core.Infrastructure;
using ZilLion.TaskManager.Entity.Config;
using ZilLion.TaskManager.Entity.Response;
using ZilLion.TaskManager.Repository;

namespace ZilLion.TaskManager.Core.SystemMonitor
{
    /// <summary>
    ///     节点心跳监控者
    ///     用于心跳通知数据库当前节点状态
    /// </summary>
    public class NodeHeartBeatMonitor : BaseMonitor
    {
        private readonly TaskNodeInfoRespository _taskNodeInfoRespository = new TaskNodeInfoRespository();

        public NodeHeartBeatMonitor()
        {
            NodeHeartBeatMonitorAction = null;
        }

        public NodeHeartBeatMonitor(Action<NodeServerResponse> nodeHeartBeatMonitorAction)
        {
            NodeHeartBeatMonitorAction = nodeHeartBeatMonitorAction;
        }

        public Action<NodeServerResponse> NodeHeartBeatMonitorAction { get; }

        public override int Interval => 5000;

        protected override void Monitor()
        {
            try
            {
                var response = _taskNodeInfoRespository.NodeHeartbeat(ZilLionConfigurationManager
                    .GetConfigInstance<TaskManagerCommonConfig>().ClientNo);
                if (response?.IsSuccess ?? false)
                {
                    if (NodeHeartBeatMonitorAction != null)
                    {
                        NodeHeartBeatMonitorAction?.Invoke(response);
                    }
                  
                    CustomTaskLogger.Print(Loglevel.Trace,
                        $"{ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().ClientNo}节点发送心跳成功");
                }

                else
                {
                    CustomTaskLogger.Print(Loglevel.Warn,
                        $"{ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().ClientNo}节点发送心跳失败");
                }
            }
            catch (Exception ex)
            {
                CustomTaskLogger.Print(ex,
                    $"{ZilLionConfigurationManager.GetConfigInstance<TaskManagerCommonConfig>().ClientNo}节点发送心跳失败");
            }
        }
    }
}